package com.processmining.support.analyseSupport.activity.json;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.processmining.support.analyseSupport.entity.SankeyActivity;
import com.processmining.support.analyseSupport.entity.SankeyDiagram;
import com.processmining.support.analyseSupport.entity.SankeyItem;

public class JsonParse {
	public static void createJsonFile(SankeyDiagram diagram,String outputPath) throws JSONException, IOException{
		JSONObject json=new JSONObject();  
	    JSONArray links = new JSONArray(); 
	    JSONArray nodes = new JSONArray(); 
		Set repeatSet=new HashSet<String>();
		for(SankeyActivity activity:diagram.getSankeyActivities()){
			String source=activity.getName();
			JSONObject node = new JSONObject(); 
			node.put("name", source);
			nodes.put(node);
			Map<Integer, List<SankeyItem>> map=activity.getOutputs();
			if(map.size()>0){
				Set<Integer> keySet=activity.getOutputs().keySet();  
			       Iterator<Integer> iterator=keySet.iterator();  
			       while(iterator.hasNext()){  
			           int key=iterator.next();  
			           List<SankeyItem> val=map.get(key); 
			           for(SankeyItem item:val){
			        	   String target=item.getName();
			        	   if(source.equalsIgnoreCase(target))//去掉自循环的路径
			        		   continue;
			        	   if(repeatSet.contains(source+target)||repeatSet.contains(target+source)){
			        		 //去掉短循环的路径
			        		   System.out.println("repeat:"+source+target);
			        		   continue;
			        	   }
			        		   JSONObject link = new JSONObject(); 
				        	   link.put("source", source);
				        	   link.put("target", item.getName());
				        	   link.put("value", item.getCounts()+"");
				        	   links.put(link);
				        	   repeatSet.add(source+target);
			           }
			       }  
			}
		}
		
		json.put("links", links);
		json.put("nodes", nodes);
		System.out.println(json.toString());
		File writeFile = new File(outputPath);
		if(writeFile.exists()){
			writeFile.delete();
		}else
		writeFile.createNewFile();
		FileWriter fw = new FileWriter(writeFile, true);
		fw.write(json.toString());
		fw.close();
	}
}
